<?php
/**
 * Goods.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */

namespace data\service;

use data\model\GoodsVarietyModel;
use data\model\NsGoodsModel;
use  think\Db;

class GoodsVariety extends BaseService
{
    public $db;

    public function __construct()
    {
        $this->db = new GoodsVarietyModel();
    }

    public function VarietyList($page_index, $page_size, $condition, $order, $field)
    {
        return $this->db->pageQuery($page_index, $page_size, $condition, $order, $field);
    }

    public function dataList($where, $num = '')
    {
        $db = $this->db->where($where);
        if ($num == 'find') {
            return $db->find();
        } else {
            return $db->select();
        }
    }

    /**
     * 级别列表
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ladder($pid = 0)
    {
        return $this->db->where(["variety_pid" => $pid])->select();

    }


    public function Varietyladder($variety_id)
    {
        $GoodsVariety = new GoodsVariety();
        $ladder = $this->db->where(['variety_id' => $variety_id])->value('ladder');
        $array = explode('@', $ladder);
        $count =(count($array)==2)?count($array):(count($array)-1);
        for ($i = 1; $i < $count; $i++) {
            $ladder = $this->db->where(['variety_id' => $array[$i]])->value('variety_pid');
            $VarietyList[$i]['key'] = $array[$i];
            $VarietyList[$i]['value'] = $GoodsVariety->ladder($ladder);
        }
        return $VarietyList;
    }

    public function Newtype($variety_id, $sort, $type)
    {
        if($type==0){
            $data =["sort"=>$sort];
        }else{
            $data =["type"=>$type];
        }
        return  $this->db->where(['variety_id' => $variety_id])->update($data);
    }

    /**
     * 添加或修改
     * @param $variety_id
     * @param $variety_name
     * @param $type
     * @param $desc
     * @param $image
     * @param int $variety_pid
     * @param string $url
     * @return bool
     */
    public function addVariety($variety_id, $variety_name, $type, $desc, $image, $variety_pid = 0, $url = '',$place='',$sort='',$_type)
    {


        $Variety = new GoodsVarietyModel();
        $Variety->startTrans();
        try {
            $id_1 = true;
            $_ladder = "0";
            if ($variety_pid) {
                $_ladder = $Variety->where("variety_id", $variety_pid)->where("variety_id",'NEQ','0')->value("ladder");
            }
            $data = [
                'variety_name' => $variety_name,
                'type' => $type,
                'desc' => $desc,
                'image' => $image,
                'variety_pid' => $variety_pid,
                'url' => $url,
                'place' => $place,
                'sort' => $sort,
            ];
            $where = [];
            if ($variety_id) {
                $where = ['variety_id' => $variety_id];
            } else {
                $data['ladder'] = 0;
            }
            $id = $Variety->save($data, $where);


            if ($variety_id) {
                $_id = $variety_id;
            } else {
                $_id = $id;
            }
            $ladder = $Variety->where("variety_id", $variety_id)->value("ladder");
            $newLadder = $_ladder . "@" . $_id;
            //修改所有下级
            $variety_id_array =  $Variety->where("locate($_id,ladder)")->column('variety_id');
            $Variety->where("variety_id",'in',$variety_id_array)->update(['type'=>$type]);
            if((count($variety_id_array)<=1)&&( rtrim($ladder,'@'.$_id)!=$newLadder)){
                //级别比对
                $new_id = $variety_id ?? $id;
                $id_1 = $Variety->where("variety_id", $new_id)->update(["ladder" => $newLadder]);
            }
            if (!$id || !$id_1 ) {
                $Variety->rollback();
                return false;
            }
            $Variety->commit();
            return $id;
        } catch (\Exception $e) {
            // 回滚事务
            $Variety->rollback();
            return false;
        }

    }

    /**
     * 删除
     * @param $variety_id
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function adelVariety($variety_id)
    {
        return $this->db->where('variety_id', $variety_id)->delete();
    }


    /**
     * 大分类商品信息列表
     * @param GoodsValidate $goodsValidate
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function HomeGoodsList($variety_id, $shop_id, $pag, $number = 10, $redis,$user_id)
    {

        $goods = new Goods();
        $GoodsVariety = new GoodsVarietyModel();
        $NsGoods = new NsGoodsModel();
        $data = [];
        if ($variety_id == 0) {
            $cache = "cacheHotSale_".$shop_id.'_'.$user_id;
            $array = $redis->get($cache);

            if(empty($array)){
                $array =  $redis->zrange("HotSale_".$shop_id.'_'.$user_id,0,-1);
                shuffle($array);
                $array = implode(',',$array);
                $redis->set($cache,$array,300);
            }

            $array = array_filter(explode(',',$array));
            $data['count'] = count($array);
            $goods_id_array = array_slice($array, ($pag - 1) * $number, $number);
            foreach ($goods_id_array as $k => $v) {
                $data['data'][] = $goods->miniatureGoodsInfo($v);
            }
        } else {
            $VarietyData = $GoodsVariety->where(["type" => 1, "variety_id" => $variety_id])->field('variety_id,variety_name,image,url')->find();
            if (empty($VarietyData)) return [];
            $data['count'] = $NsGoods->where(['variety_id' => $VarietyData['variety_id'], 'state' => 1, 'goods_type_crowd' => 0, 'shop_id' => $shop_id])->count();
            $data['variety'] = $VarietyData->toArray();
            $goods_id_array = $NsGoods->where(['variety_id' => $VarietyData['variety_id'], 'state' => 1, 'goods_type_crowd' => 0, 'shop_id' => $shop_id])->page($pag, $number)->column('goods_id');
            foreach ($goods_id_array as $k => $v) {
                $data['data'][] =$d= $goods->miniatureGoodsInfo($v);
            }

        }
        return $data;
    }

    /**
     * 自定义分类列表
     * @param $variety_id id
     * @param $level 层级
     * @param $pag 分页页数
     * @param $number 分页条数
     * @param $where 条件
     * @param $order  排序
     * @param $field 字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function HomeVarietyList($variety_id, $level, $pag, $number, $where, $order, $field)
    {
        $_where = '';
        if ($variety_id) {
            $_where = "locate($variety_id,ladder) AND length(ladder)-length(replace(ladder,'@',''))={$level}";
        }
        $VarietyData = $this->db->where($where)->where($_where)->field($field)->order($order)->page($pag, $number)->select();
        $data['count'] = $this->db->where($where)->where($_where)->count();
        if (empty($VarietyData)) return [];
        foreach ($VarietyData as $k => $v) {
            $f_variety_id = explode('@', $v['ladder'])[1];
            $VarietyData[$k]['f_variety_name'] = $this->db->where(["variety_id" => $f_variety_id])->value('variety_name');
            unset($VarietyData[$k]['ladder']);
        }
        $data['data'] = $VarietyData;
        return $data;
    }


}